package tool

import (
	"encoding/json"
	"reflect"
	"sort"
)

//结构体转[]map
func StructToSinceMap(data interface{}) ([]map[string]interface{}, error) {
	jsonData, errJ := json.Marshal(data)
	if errJ != nil {
		return nil, errJ
	}
	var mapData []map[string]interface{}
	errU := json.Unmarshal(jsonData, &mapData)
	if errU != nil {
		return nil, errU
	}
	return mapData, nil
}

//结构体转[]map
func StructToMap(data interface{}) (map[string]interface{}, error) {
	jsonData, errJ := json.Marshal(data)
	if errJ != nil {
		return nil, errJ
	}
	var mapData map[string]interface{}
	errU := json.Unmarshal(jsonData, &mapData)
	if errU != nil {
		return nil, errU
	}
	return mapData, nil
}

//结构体转另一个接口体第二个参数是指针类型
func StructToStruct(data interface{}, resData interface{}) error {
	jsonData, errJ := json.Marshal(data)
	if errJ != nil {
		return errJ
	}
	errU := json.Unmarshal(jsonData, resData)
	if errU != nil {
		return errU
	}
	return nil
}

//递归排序
func SortMapByKey(data interface{}) (map[string]interface{}, []string) {
	var count int
	var keys []string
	var keyfirst []string
	dataMap, ok := data.(map[string]interface{})
	if !ok {
		return dataMap, keys
	}
	dataMap, keys = KSort(dataMap)
	count++
	if count == 1 {
		keyfirst = keys
	}
	keyfirst = keys
	for k, v := range dataMap {
		if reflect.ValueOf(v).Kind() == reflect.Map {
			resMap := make(map[string]interface{})
			resMap, keys = SortMapByKey(v)
			dataMap[k] = resMap
		}
	}

	return dataMap, keyfirst
}

//map排序
func KSort(data interface{}) (map[string]interface{}, []string) {
	keys := []string{}
	dataSortMap, ok := data.(map[string]interface{})
	if !ok {
		return dataSortMap, keys
	}

	for k, _ := range dataSortMap {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	newMap := make(map[string]interface{})
	for _, v := range keys {
		newMap[v] = dataSortMap[v]
	}
	return newMap, keys

}
